#include <arpa/inet.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>

#include <cstring>
#include <iostream>

int main() {
  /**
   * 1. 创建服务端socket，并绑定相应ip和端口
   *    SOCK_STREAM对应的是TCP协议，安全可靠；SOCK_DGRAM是UDP协议，不可靠
   *    listen使得该进程可以接收socket的请求，成为一个服务端。对应的是客户端的connect。
  */
  int sock_server = socket(AF_INET, SOCK_STREAM, 0);
  sockaddr_in server_addr;
  memset(&server_addr, 0, sizeof(server_addr));
  server_addr.sin_family = AF_INET;
  server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
  server_addr.sin_port = htons(8888);
  bind(sock_server, (struct sockaddr *)&server_addr, sizeof(server_addr));
  listen(sock_server, 5);

  // 2. 服务端接受客户端的请求
  int socklen = sizeof(struct sockaddr_in);
  sockaddr_in client_addr;
  int sock_client = accept(sock_server, (struct sockaddr *)&client_addr,
                           (socklen_t *)&socklen);
  printf("client %s has connnected\n", inet_ntoa(client_addr.sin_addr));

  // 3. 同客户端连接，并接受数据
  char buffer[50];
  while (1) {
    memset(buffer, 0, sizeof(buffer));
    recv(sock_client, buffer, sizeof(buffer), 0);
    printf("receive: %s\n", buffer);

    strcpy(buffer, "I'm fine, thx!");
    send(sock_client, buffer, strlen(buffer), 0);
    printf("send   : %s\n", buffer);
  }
  // 4. 关闭
  close(sock_server);
  close(sock_client);
  return 0;
}
